/**
 * @file filter
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import {render, filter, evalExpression} from '../renderer';
import * as cx from 'classnames';
import * as assign from 'object-assign';
import * as omit from 'lodash/omit';
import * as pick from 'lodash/pick';
import FormItem from './form-item';
import {
  Row,
  Col
} from 'react-bootstrap';

const ColProps = [
  'lg',
  'lgHidden',
  'lgOffset',
  'lgPull',
  'lgPush',

  'md',
  'mdHidden',
  'mdOffset',
  'mdPull',
  'mdPush',

  'sm',
  'smHidden',
  'smOffset',
  'smPull',
  'smPush',

  'xs',
  'xsHidden',
  'xsOffset',
  'xsPull',
  'xsPush'
];

@FormItem({
  type: 'grid',
  hideLabelByDefault: true,
  attachForm: false,
  validateSchema: false // "http://amis.baidu.com/schemas/form.json#/definitions/grid"
})
export default class GridFormItem extends PureComponent {
  static propTypes = {
    className: PropTypes.string
  };

  static defaultProps = {
    className: ''
  };

  renderColumn(column, key, length, subProps) {
    const {
      $path,
      mode,
      formMode,
      horizontal,
      horizontalDeeper
    } = this.props;

    const md = Math.floor(12/length);

    const colProps = pick(Array.isArray(column) ? {
      md
    } : assign({}, {
      md
    }, column), ColProps);

    return (
      <Col
        key={key}
        {...colProps}
      >
        {
          column.type ? render(`${$path}/${column.type}`, column, assign({}, subProps, {
              $index: key
          })) : render(`${$path}/basic-form`, column, assign({}, subProps, {
            $index: key,
            elementsOnly: true,
            mode: column.mode || mode || formMode,
            horizontal: column.horizontal || horizontal,
            horizontalDeeper: column.horizontalDeeper || horizontalDeeper
          }))
        }
      </Col>
    );
  }

  render() {
    const {
      className,
      columns,
      data
    } = this.props;

    const subProps = omit(this.props, ['className', 'columns'].concat(ColProps));

    return (
      <div className={cx('row', className)}>
        {columns
          .filter(item => item.visibleOn ? evalExpression(item.visibleOn, data)
            : item.hiddenOn ? !evalExpression(item.hiddenOn, data) : true)
          .map((column, key) => this.renderColumn(
            column, key, columns.length, subProps
          ))
        }
      </div>
    );
  }
}
